package com.springBoot.springBootSysCore.common.third.oss;

import com.springBoot.springBootSysCore.common.config.Global;
import com.springBoot.springBootSysCore.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.net.URL;

/**
 * Created by timo on 2018/1/5.
 */
public class OssUpload {

    static String endpoint ;
    static String accessId ;
    static String accessKey ;
    static String bucket;
    static String upfile_defaltdir ;

    public static Object upload(File file){
        if(StringUtils.isBlank(endpoint)){
            init();
        }
        String endpoints = "http://" + endpoint;
        com.aliyun.oss.OSSClient client = new com.aliyun.oss.OSSClient(endpoints, accessId, accessKey);
        client.putObject(bucket, upfile_defaltdir+file.getName(), file);
        URL url = client.generatePresignedUrl(bucket,upfile_defaltdir+file.getName(), DateUtils.parseDate(DateUtils.getDateAfterWhatMS(new java.util.Date(),36500)));
        return url;
    }

    private static void init() {
        endpoint = Global.getConfig("oss.endpoint");
        accessId = Global.getConfig("oss.accessKeyId");
        accessKey  = Global.getConfig("oss.accessKeySecret");
        bucket = Global.getConfig("oss.bucketName");
        upfile_defaltdir = Global.getConfig("oss.upfile_defaltdir");
    }
}
